/**
 * 减少函数调用次数
 * https://github.com/PanJiaChen/vue-element-admin/blob/master/src/utils/index.js#L247
 *
 * @param {Function} func 被调函数
 * @param {number} wait 最小间隔
 * @param {boolean} immediate 是否立刻执行
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * Parse the time to string
 * https://github.com/PanJiaChen/vue-element-admin/blob/master/src/utils/index.js#L11
 *
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export class TypeAnalyzer {
  types = []
  enriched = []
  constructor(types) {
    this.types = types
  }

  findType(id) {
    return this.types.find(item => item.id === id)
  }

  findParent(type) {
    return this.types.find(item => item.id === type.parent_type_id)
  }

  buildParentPath(type) {
    const path = [type.id]
    let curr = type
    while (curr.parent_type_id !== 0) {
      const parent = this.findParent(curr)
      if (!parent) {
        throw new Error('类型树结构错误')
      }
      path.unshift(parent.id)
      curr = parent
    }
    return path
  }

  buildPathText(path) {
    return path
      .map(id => this.findType(id))
      .map(type => '/' + type.type_name)
      .join('')
  }

  analyze() {
    this.enriched = this.types.map(type => {
      const path = this.buildParentPath(type)
      const text = this.buildPathText(path)
      return {
        ...type,
        path,
        text
      }
    })
    return this.enriched
  }
}

export class SystemConfigure {
  descriptions
  constructor(descriptions) {
    this.descriptions = descriptions
  }

  load(commit) {
    if (window.localStorage) {
      for (const desp of this.descriptions) {
        try {
          const key = 'config_' + desp.name
          if (window.localStorage.getItem(key) === null) {
            window.localStorage.setItem(key, JSON.stringify(desp.default))
          }
          const value = window.localStorage.getItem(key)
          commit(desp.mutation, JSON.parse(value))
        } catch (err) {
          console.warn(err)
        }
      }
    }
  }

  /**
   * 保存配置值
   * @param {*} item 配置项的name或mutation或索引
   * @param {*} value 配置项值
   */
  write(item, value) {
    if (window.localStorage) {
      var name
      if (typeof item === 'number') {
        name = this.descriptions[item].name
      } else {
        const desp = this.descriptions.find(it => it.mutation === item) || this.descriptions.find(it => it.name === item)
        name = desp.name
      }
      const key = 'config_' + name
      window.localStorage.setItem(key, JSON.stringify(value))
    }
  }
}

/**
 * 将以base64的图片url数据转换为Blob
 * https://www.cnblogs.com/zhaoyingjie/p/8451946.html
 *
 * @param urlData 用url方式表示的base64图片数据
 */
export function convertBase64UrlToBlob(urlData, type = 'image/png') {
  var bytes = window.atob(urlData.split(',')[1]) // 去掉url的头，并转换为byte
  // 处理异常,将ascii码小于0的转换为大于0
  var ab = new ArrayBuffer(bytes.length)
  var ia = new Uint8Array(ab)
  for (var i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i)
  }
  return new Blob([ab], { type })
}

export function convertCreateQuestionStatusToButtonInfo(status) {
  if (status.submitting) {
    return {
      text: '上传中……',
      color: 'success'
    }
  } else {
    if (status.question) {
      if (status.image) {
        return {
          text: '成功',
          color: 'success'
        }
      } else {
        return {
          text: '重试上传图片',
          color: 'orange'
        }
      }
    } else {
      return {
        text: '确认提交',
        color: 'success'
      }
    }
  }
}
